package beer.zivelin.awesome.walawala.mobile.ui;

import android.app.Activity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.ViewGroup;
import android.widget.Button;

import java.util.List;

import beer.zivelin.awesome.walawala.mobile.entity.ApplicationData;
import beer.zivelin.awesome.walawala.mobile.service.ApplicationLocator;

public class SearchEditorWatcher implements TextWatcher {
    ViewGroup appSearchResultView;
    ApplicationLocator locator;
    Activity activity;
    Button searchLikeBt;

    public SearchEditorWatcher(ViewGroup appSearchResultView, ApplicationLocator locator, Button searchLikeBt, Activity activity) {
        this.appSearchResultView = appSearchResultView;
        this.locator = locator;
        this.searchLikeBt = searchLikeBt;
        this.activity = activity;
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        String text = s.toString();
        searchApp(text);
        if (text == null || "".equals(text)) {
            ApplicationViewHelper.setSearchLikeButtonStatus(searchLikeBt, ApplicationViewHelper.SEARCH_LIKE_BUTTON_ST_INIT);
        } else if (text.startsWith(ApplicationLocator.LIKE_MODE_PREFIX)) {
            ApplicationViewHelper.setSearchLikeButtonStatus(searchLikeBt, ApplicationViewHelper.SEARCH_LIKE_BUTTON_ST_LIKE);
        } else {
            ApplicationViewHelper.setSearchLikeButtonStatus(searchLikeBt, ApplicationViewHelper.SEARCH_LIKE_BUTTON_ST_NORMAL);
        }
    }

    public void searchApp(String t9Spell) {
        List<ApplicationData> applicationInfoList = locator.match(t9Spell);
        appSearchResultView.removeAllViews();
        ApplicationViewHelper.drawAppOnView(applicationInfoList, appSearchResultView, activity);
    }


}
